package com.dzsw.security;

import cn.hutool.core.util.StrUtil;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

public class MyAuthProvider extends AbstractUserDetailsAuthenticationProvider {

    @Override
    protected void additionalAuthenticationChecks(UserDetails userDetails, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (StrUtil.isEmpty(userDetails.getUsername())) {
            throw new UsernameNotFoundException("Username is empty");
        }
    }

    @Override
    protected UserDetails retrieveUser(String username, UsernamePasswordAuthenticationToken authentication) throws AuthenticationException {
        if (StrUtil.isEmpty(username)) {
            throw new UsernameNotFoundException("Username is empty");
        }
        if (!StrUtil.equals(username, "user")) {
            throw new UsernameNotFoundException("user name not found.");
        }
        if (!StrUtil.equals("123456", authentication.getCredentials().toString())) {
            throw new BadCredentialsException("pwd is fault.");
        }
        return new User(username, authentication.getCredentials().toString(), authentication.getAuthorities());
    }
}
